package com.neudu.yiyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.yiyang.commons.JSONReturn;
import com.neudu.yiyang.pojo.Customer;
import com.neudu.yiyang.service.CustomerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class CustomerController {
    private static final Logger logger = LoggerFactory.getLogger(CustomerController.class);
    @Autowired
    private CustomerService customerService;
    @Autowired
    private JSONReturn jsonReturn;

    // 查询所有客户信息
    @PostMapping("get_all_customers")
    public String getAll(@RequestBody PageInfo pageInfo, @RequestParam(required = false) String status) {
        logger.info("进入查询所有客户信息接口");
        try {
            PageHelper.startPage(pageInfo.getPageNum(), pageInfo.getPageSize());
            LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
            if (!ObjectUtils.isEmpty(status)) {
                if ("in".equals(status)) {
                    queryWrapper.eq(Customer::getState, 1);
                } else if ("out".equals(status)) {
                    queryWrapper.eq(Customer::getState, 2);
                }
            }
            List<Customer> list = customerService.list(queryWrapper);
            PageInfo<Customer> pageInfoReturn = new PageInfo<>(list);
            logger.info("接收到的客户状态参数: {}", status);
            return jsonReturn.returnSuccess(pageInfoReturn);
        } catch (Exception e) {
            logger.error("查询所有客户信息时发生异常", e);
            return handleException(e);
        }
    }

    // 根据条件查询客户信息
    @PostMapping("get_customers_by")
    public String getByCondition(@RequestBody Customer customer, @RequestParam(required = false) String status) {
        logger.info("进入根据条件查询客户信息接口");
        try {
            LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
            if (customer != null) {
                queryWrapper.eq(!ObjectUtils.isEmpty(customer.getId()), Customer::getId, customer.getId())
                        .eq(!ObjectUtils.isEmpty(customer.getCustomerAge()), Customer::getCustomerAge, customer.getCustomerAge())
                        .eq(!ObjectUtils.isEmpty(customer.getCustomerSex()), Customer::getCustomerSex, customer.getCustomerSex())
                        .like(!ObjectUtils.isEmpty(customer.getCustomerName()), Customer::getCustomerName, customer.getCustomerName())
                        .eq(!ObjectUtils.isEmpty(customer.getBuildingNo()), Customer::getBuildingNo, customer.getBuildingNo());
            }
            if (!ObjectUtils.isEmpty(status)) {
                if ("in".equals(status)) {
                    queryWrapper.eq(Customer::getState, 1);
                } else if ("out".equals(status)) {
                    queryWrapper.eq(Customer::getState, 2);
                }
            }
            List<Customer> customers = customerService.list(queryWrapper);
            return jsonReturn.returnSuccess(customers);
        } catch (Exception e) {
            logger.error("根据条件查询客户信息时发生异常", e);
            return handleException(e);
        }
    }

    // 添加一个客户信息
    @PostMapping("add_one_customer")
    public String addOne(@RequestBody Customer customer) {
        logger.info("进入添加客户信息接口");
        try {
            customerService.save(customer);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            logger.error("添加客户信息时发生异常", e);
            return handleException(e);
        }
    }

    // 根据id查询客户信息
    @PostMapping("getcustomerby_id")
    public String getById(@RequestParam("customerid") Integer customerid) {
        logger.info("进入根据id查询客户信息接口");
        try {
            Customer customer = customerService.getById(customerid);
            return jsonReturn.returnSuccess(customer);
        } catch (Exception e) {
            logger.error("根据id查询客户信息时发生异常", e);
            return handleException(e);
        }
    }

    // 根据id修改客户信息
    @PostMapping("modifycustomerby_id")
    public String modifyById(@RequestBody Customer customer) {
        logger.info("进入根据id修改客户信息接口");
        try {
            customerService.updateById(customer);
            return jsonReturn.returnSuccess(customer);
        } catch (Exception e) {
            logger.error("根据id修改客户信息时发生异常", e);
            return handleException(e);
        }
    }

    // 根据id删除客户信息
    @PostMapping("removecustomer_by_id")
    public String removeByid(@RequestParam("customerid") Integer customerid) {
        logger.info("进入根据id删除客户信息接口");
        try {
            customerService.removeById(customerid);
            return jsonReturn.returnSuccess();
        } catch (Exception e) {
            logger.error("根据id删除客户信息时发生异常", e);
            return handleException(e);
        }
    }

    // 新增获取客户列表的方法
    @GetMapping("/get_Customer_List")
    public String getCustomerList(@RequestParam(required = false) String status) {
        logger.info("进入获取客户列表接口");
        try {
            QueryWrapper<Customer> wrapper = new QueryWrapper<>();
            if (!ObjectUtils.isEmpty(status)) {
                if ("in".equals(status)) {
                    wrapper.eq("state", 1);
                } else if ("out".equals(status)) {
                    wrapper.eq("state", 2);
                }
            }
            List<Customer> customerList = customerService.list(wrapper);
            return jsonReturn.returnSuccess(customerList);
        } catch (Exception e) {
            logger.error("获取客户列表时发生异常", e);
            return handleException(e);
        }
    }

    // 统一的异常处理方法
    private String handleException(Exception e) {
        return jsonReturn.returnError(e.getMessage());
    }

    @RequestMapping("/customer/list")
    public String getCustomers(String customerName) {
        try{
            LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(!ObjectUtils.isEmpty(customerName),Customer::getCustomerName, customerName)
                    .eq(Customer::getIsDeleted, 0);
            List<Customer> list = customerService.list(queryWrapper);
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("/customer/detail")
    public String getCustomerDetailsByName(String customerName) {
        try{
            List<Customer> list = customerService.getCustomerDetailsByName(customerName);
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }


    @RequestMapping("/customer/listByUserId")
    public String getCustomersByUserId(Integer userId) {
        try{
            List<Customer> list = customerService.getCustomerByUserId(userId);
            return jsonReturn.returnSuccess(list);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }

    @RequestMapping("/customer/update")
    public String update(@RequestBody Customer customer){
        try{
            boolean update = customerService.updateById(customer);
            if(update){
                return jsonReturn.returnSuccess();
            }else{
                return jsonReturn.returnFailed();
            }
        }catch(Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    // 添加护理人员
    @RequestMapping("/customer/addUser")
    public String addUser(Integer userId, String customerIds){
        try{
            if (customerIds == null || userId == null) {
                return jsonReturn.returnError("Invalid parameters");
            }
            // 将逗号分隔的字符串转换为整数数组
            String[] itemsArray = customerIds.split(",");
            Integer[] itemsId = new Integer[itemsArray.length];
            for(int i = 0; i < itemsArray.length; i++) {
                itemsId[i] = Integer.parseInt(itemsArray[i]);
            }
            for (Integer itemId : itemsId){
                if (itemId == null){
                    continue;
                }
                Customer customer = new Customer();
                customer.setId(itemId);
                customer.setUserId(userId);
                boolean save = customerService.updateById(customer);
                if (!save){
                    return jsonReturn.returnFailed();
                }
            }
            return jsonReturn.returnSuccess();
        }catch(Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
    // 删除护理人员
    @RequestMapping("/customer/deleteUser")
    public String deleteUser(Integer customerId){
        try{
            Customer customer = new Customer();
            customer.setId(customerId);
            customer.setUserId(-1);
            boolean delete = customerService.updateById(customer);
            if (delete){
                return jsonReturn.returnSuccess();
            }else{
                return jsonReturn.returnFailed();
            }
        } catch (Exception e){
            e.printStackTrace();
            return jsonReturn.returnError(e.getMessage());
        }
    }
}